package com.zf.yichat.api.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.cloudauth20190307.models.DescribeFaceVerifyResponse;
import com.aliyun.cloudauth20190307.models.InitFaceVerifyResponse;
import com.aliyun.oss.ServiceException;
import com.zf.yichat.api.config.interceptor.LogRecordAspect;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.*;
import com.zf.yichat.api.dto.resp.*;
import com.zf.yichat.dto.*;
import com.zf.yichat.im.mapper.RcUsersMapper;
import com.zf.yichat.mapper.UserBalanceMapper;
import com.zf.yichat.mapper.UserIntegralDetailMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.mapper.WxWalletCoinMapper;
import com.zf.yichat.model.*;
import com.zf.yichat.service.*;
import com.zf.yichat.service.config.ConfigSet;
import com.zf.yichat.service.config.RedisService;
import com.zf.yichat.service.impl.UserValidServiceImpl;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.*;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.DictKey;
import com.zf.yichat.vo.IntegralType;
import com.zf.yichat.vo.UserStatusEnum;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.TextUtils;
import org.hibernate.validator.internal.util.Contracts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户相关接口
 *
 * @author fengsong
 * @date create in 09:52 2019/5/31 2019
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    private UserInviteService userInviteService;
    @Resource
    private RedisService redisService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserValidService userValidService;

    @Resource
    private RcUsersMapper rcUsersMapper;

    @Autowired
    private FriendService friendService;

    @Autowired
    private BalanceService balanceService;

    @Autowired
    private UserWithdrawService userWithdrawService;

    @Autowired
    private AppConfigService appConfigService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private ConfigSet configSet;

    @Autowired
    private SecurityService securityService;

    @Resource
    private UserBalanceMapper userBalanceMapper;

    @Resource
    private WxWalletCoinMapper wxWalletCoinMapper;

    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private PlantTreeService plantTreeService;

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserIntegralDetailMapper userIntegralDetailMapper;

    // 融云服务配置项
    @Value("${rongcloud.key}")
    private String RONGCLOUD_KEY;
    @Value("${rongcloud.secret}")
    private String RONGCLOUD_SECRET;

    @Value("${st.im_uri}")
    private String imUri;

    /**
     * 搜索用户 完全匹配手机号或appid
     */
    @PostMapping("/search")
    public FsResponse search(@RequestBody UserSearchRequest params) {

        List<UserSearchDto> dtos = null;
        if (StringUtils.isNotBlank(params.getContent())) {
            List<User> copys = userService.searchByMobileOrAppId(params.getContent());
            if (GeneralUtils.isNotNullOrEmpty(copys)) {
                dtos = copys.stream().map(copy -> {
                    UserSearchDto dto = new UserSearchDto();
                    dto.setGender(copy.getGender());
                    try {
                        dto.setUserId(N3d.encode(copy.getId()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    dto.setAvatar(copy.getAvatar());
                    dto.setNick(copy.getNick());
                    dto.setAppId(copy.getAppid());
                    //0好友关系 1否
                    dto.setFriendStatus(friendService.isFriend(getUserId(), copy.getId()) ? 0 : 1);
                    return dto;
                }).collect(Collectors.toList());
            }
        }

        return FsResponseGen.successData(dtos);
    }
    @PostMapping("/version")
    public FsResponse version() {
         JSONObject jsonObject=new JSONObject();
        String homeUrl=   Optional.ofNullable(sysDictService.selectOne(DictKey.url_home_website)).map(SysDict::getValue).orElse("");
        String androidUrl=   Optional.ofNullable(sysDictService.selectOne(DictKey.url_android_apk)).map(SysDict::getValue).orElse("");
        String androidVersion=Optional.ofNullable(sysDictService.selectOne(DictKey.url_android_apk)).map(SysDict::getMemo).orElse("");
        String iosUrl=   Optional.ofNullable(sysDictService.selectOne(DictKey.url_ios_ipa)).map(SysDict::getValue).orElse("");
        String iosVersion=Optional.ofNullable(sysDictService.selectOne(DictKey.url_ios_ipa)).map(SysDict::getMemo).orElse("");
        jsonObject.put("homeUrl",homeUrl);
        jsonObject.put("androidUrl",androidUrl);
        jsonObject.put("androidVersion",androidVersion);
        jsonObject.put("iosUrl",iosUrl);
        jsonObject.put("iosVersion",iosVersion);
        return FsResponseGen.successData(jsonObject);
    }


    @PostMapping("/serviceUrl")
    public FsResponse serviceUrl() {
         String serviceUrl= Optional.ofNullable(sysDictService.selectOne(DictKey.sys_service_url_0)).map(SysDict::getMemo).orElse("");
        String serviceUrl_1= Optional.ofNullable(sysDictService.selectOne(DictKey.sys_service_url_1)).map(SysDict::getMemo).orElse("");
        String serviceUrl_2= Optional.ofNullable(sysDictService.selectOne(DictKey.sys_service_url_2)).map(SysDict::getMemo).orElse("");

        User user=userService.selectById(getUserId());
         if(user!=null){
             String useravatar=user.getAvatar();
             if(useravatar!=null&&useravatar.startsWith("http://")){
                 useravatar=useravatar.replace("http://","https://");
             }
             serviceUrl=serviceUrl+"?openId="+ user.getId()+"&nickname="+user.getNick()+"&avatarUrl="+useravatar;
         }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("serviceUrl",serviceUrl);
        return FsResponseGen.successData(jsonObject);
    }
    @PostMapping("/officialWebsite")
    public FsResponse officialWebsite(@RequestBody UserInfoRequest request222) throws Exception {

        String url= Optional.ofNullable(sysDictService.selectOne(DictKey.sys_dic_guangwang)).map(SysDict::getValue).orElse(null);


        return FsResponseGen.successData(url);
    }

    @PostMapping("/downloadurl")
    public FsResponse sys_dic_downloadurl(@RequestBody UserInfoRequest request222) throws Exception {

        String url= Optional.ofNullable(sysDictService.selectOne(DictKey.sys_dic_downloadurl)).map(SysDict::getValue).orElse(null);


        return FsResponseGen.successData(url);
    }
    @PostMapping("/mygameUrl")
    public FsResponse mygameUrl(@RequestBody UserInfoRequest request222) throws Exception {
        if (!userService.realValidStatus(getUserId())) {

            return FsResponseGen.failMsg("请先实名认证");
        }
        String parter_for_game   = Optional.ofNullable(sysDictService.selectOne(DictKey.parter_for_game)).map(SysDict::getValue).orElse("0");
        if("1".equals(parter_for_game)){
            User userCheck=userService.selectById(getUserId());
            if(userCheck.getLevel()==null||userCheck.getLevel()==0){
                return FsResponseGen.failMsg("请先成为合伙人");
            }
        }




        // 查询今日玩游戏获取的积分值是否高于设置的阈值
        // 每日玩游戏获取积分的最大值
        String thresholdScores = sysDictService.selectOne(DictKey.sys_dict_game_threshold).getValue();
        if (StringUtils.isBlank(thresholdScores)) {
            thresholdScores = "100";
        }


        //查询配置的玩游戏获取积分
        String score = sysDictService.selectOne(DictKey.sys_dict_game_threshold_single).getValue();
        if (StringUtils.isBlank(score)) {
            score = "10";
        }
        String url=          Optional.ofNullable(sysDictService.selectOne(DictKey.sys_dic_game_url)).map(SysDict::getValue).orElse(null);
        url=url+"?uid="+N3d.encode(getUserId());
        JSONObject data=new JSONObject();
        data.put("url",url);
        data.put("singleNum",score);
        data.put("maxNum",thresholdScores);

        return FsResponseGen.successData(data);
    }



    private void batchUpdateUserBalance (List<WxWalletCoin> data) {
        if (data != null && !data.isEmpty ()) {

            ArrayList<UserBalance> userBalances = new ArrayList<>();

            for (WxWalletCoin item : data) {
                BigDecimal balance = new BigDecimal (item.getCny ()).divide (new BigDecimal (100)).multiply (new BigDecimal ("7.06")).setScale (2, BigDecimal.ROUND_CEILING);
                Integer uid = item.getUid();

                UserBalance userBalance = new UserBalance();
                userBalance.setUserId(uid.longValue());
                userBalance.setBalance(balance);  // 将计算出来的金额保存到对象中
                userBalance.setFreezeBalance(new BigDecimal("0"));
                userBalance.setIncomeBalance(balance);  // 将计算出来的金额保存到对象中
                userBalances.add(userBalance);
            }
            userBalanceMapper.batchUpdateUserBalance (userBalances);  // 调用批量更新方法完成更新
        }
    }

    /**
     * 搜索用户 完全匹配手机号或appid
     */
    @RequestMapping("/test/user2")
    public FsResponse testUser2(@RequestBody UserSearchRequest params) {

        Example example=new Example(WxWalletCoin.class);
        example.createCriteria().andGreaterThan("cny",0);


        List<WxWalletCoin> data=wxWalletCoinMapper.selectByExample(example);
//        insertData(0,data);
        batchUpdateUserBalance (data);

        return FsResponseGen.successData(null);
    }
    @RequestMapping("/blockByAdmin")
    public FsResponse blockByAdmin(@RequestBody  UserInfoRequest userInfoRequest) {
        String userId = userInfoRequest.getUserId();

        securityService.clearToken(Long.valueOf(userId));


        return FsResponseGen.successData(null);
    }


    private void insertData(int index, List<WxWalletCoin> data){
        if(index>data.size()-1){
            return;
        }
        WxWalletCoin wxWalletCoin=data.get(index);
        if(wxWalletCoin!=null){
            long uid=wxWalletCoin.getUid();
            BigDecimal money=(new BigDecimal(wxWalletCoin.getCny()).divide(new BigDecimal("100"))).multiply(new BigDecimal("7.02")).setScale(2, BigDecimal.ROUND_CEILING);
            userBalanceMapper.updateBalance(uid,money,new BigDecimal("0"),money);
            index++;
            insertData(  index,  data);

        }
    }

    /**
     * 查询用户资料
     * @param request222
     * @return
     * @throws Exception
     */
    @PostMapping("/info")
    public FsResponse info(@RequestBody UserInfoRequest request222) throws Exception {
        Long userIdParamLong =getUserId();
        if(request222.getUserId()!=null){
            userIdParamLong=   N3d.decode(request222.getUserId());
        }

//        if(request.getUserId()!=null){
//            Long userIdParamLong = N3d.decode(request.getUserId());
//
//            if(!userIdParamLong.equals(getUserId())){
//                return FsResponseGen.fail(YiChatMsgCode.USER_INFO_NONE);
//            }
//        }


        User user = userService.selectById( userIdParamLong);
        if (Objects.isNull(user) || Objects.isNull(user.getId())) {
            return FsResponseGen.fail(YiChatMsgCode.USER_INFO_NONE);
        }
        Contracts.assertNotNull(UserStatusEnum.isOpen(user.getStatus()), YiChatMsgCode.SYSTEM_USER_CLOSE.msg());

        UserInfoDto userInfoDto = new UserInfoDto();
        userInfoDto.setIntegral(user.getIntegral());
        userInfoDto.setAppId(user.getAppid());
        userInfoDto.setRecommendCode(user.getRecommendCode());
        userInfoDto.setUcode(user.getUcode());
        userInfoDto.setMobile(user.getMobile());
        userInfoDto.setAvatar(user.getAvatar());
        userInfoDto.setNick(user.getNick());
        if(Objects.isNull(user.getLevel())){
            userInfoDto.setLevel(0);
        }else {
            userInfoDto.setLevel(user.getLevel());
        }
        SysDict sysDict = sysDictService.selectOne(DictKey.user_activate_member_ship_money);
         if(sysDict!=null){
             userInfoDto.setVipMoney(sysDict.getValue());
         }
        userInfoDto.setUserId(N3d.encode(user.getId()));
        userInfoDto.setGender(user.getGender());
        userInfoDto.setUserIdInner(user.getId()+"");
        userInfoDto.setSign(user.getRemark());
//        if (Objects.isNull(userIdParamLong) || userIdParamLong.equals(getUserId())) {
//            userInfoDto.setMobile(user.getMobile());
//            userInfoDto.setRealName(user.getRealName());
//            userInfoDto.setIdNumber(user.getIdNumber());
//            userInfoDto.setValidStatus(user.getRealStatus());
//            userInfoDto.setAlipayAccount(user.getAlipayAccount());
//            userInfoDto.setZfAccount(user.getAlipayAccount());
//            userInfoDto.setImToken(rcUsersMapper.selectByPrimaryKey(user.getId().intValue()).getRongcloudtoken());
//        }
     //   userInfoDto.setPayPasswordStatus(StringUtils.isNotBlank(balanceService.selectByUserId(getUserId()).getPassword()) ? 1 : 0);
        //获取好友备注
//        userInfoDto.setFriendStatus(0);
//        if (Objects.nonNull(request.getUserId()) && N3d.decode(request.getUserId()) != getUserId()) {
//            Friend friend = friendService.selectOne(getUserId(), N3d.decode(request.getUserId()));
//            //0好友关系 1否
//            if (Objects.nonNull(friend)) {
//                userInfoDto.setRemark(friend.getUserId().compareTo(getUserId()) == 0 ? friend.getUserMark() : friend.getFriendMark());
//            } else {
//                userInfoDto.setRemark("");
//                userInfoDto.setFriendStatus(1);
//            }
//
//        }

        return FsResponseGen.successData(userInfoDto);
    }

    @PostMapping("/info_for_mh")
    public FsResponse infoForManghe(@RequestBody UserInfoRequest request) throws Exception {
        if (!"gdsalgndiosamw39t0gndss.gdjgdl".equals(request.getVerifyToken())) {
            return FsResponseGen.fail();
        }
        Long userIdParamLong;
        if (Objects.nonNull(request.getToken())) {
            FsResponse fsResponse = securityService.getUserIdByToken(request.getToken());
            if (!fsResponse.isSuccess()) {
                return fsResponse;
            }
            userIdParamLong = (Long) fsResponse.getData();
        } else if (Objects.nonNull(request.getUserId())) {
            userIdParamLong = N3d.decode(request.getUserId());
        } else {
            return FsResponseGen.fail(YiChatMsgCode.SYSTEM_PARAM_ERROR);
        }

        User user = userService.selectById(userIdParamLong);
        if (Objects.isNull(user) || Objects.isNull(user.getId())) {
            return FsResponseGen.fail(YiChatMsgCode.USER_INFO_NONE);
        }
        Contracts.assertNotNull(UserStatusEnum.isOpen(user.getStatus()), YiChatMsgCode.SYSTEM_USER_CLOSE.msg());

        UserInfoDto userInfoDto = new UserInfoDto();
        userInfoDto.setIntegral(user.getIntegral());
        userInfoDto.setAppId(user.getAppid());
        userInfoDto.setRecommendCode(user.getRecommendCode());
        userInfoDto.setUcode(user.getUcode());
        userInfoDto.setAvatar(user.getAvatar());
        userInfoDto.setNick(user.getNick());
        userInfoDto.setUserId(N3d.encode(user.getId()));
        userInfoDto.setGender(user.getGender());
        logger.debug("返回给盲盒的用户数据===>>", JSON.toJSONString(userInfoDto));
        return FsResponseGen.successData(userInfoDto);
    }
    private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

    /**
     * 用户资料更新
     */
    @PostMapping("info/update")
    @Transactional(rollbackFor = Exception.class)
    public FsResponse update(@RequestBody UserInfoUpdateRequest params) {
        params.valid();

        //未登录情况下修改密码 重置密码
//        if (getUserId() == null && StringUtils.isNotBlank(params.getMobile()) && StringUtils.isNotBlank(params.getPassword())) {
//            User src = userService.selectByMobile(params.getMobile());
//            Contracts.assertNotNull(src, YiChatMsgCode.SYSTEM_ERROR.msg());
//            Contracts.assertNotNull(UserStatusEnum.isOpen(src.getStatus()), YiChatMsgCode.SYSTEM_USER_CLOSE.msg());
//
//
//            User user = new User();
//            user.setId(src.getId());
//            user.setPassword(MD5Util.shaEncode(params.getPassword()));
//            userService.update(user);
//
//            //清除登录token
//            //securityService.clearToken(getUserId());
//
//            return FsResponseGen.success();
//
//        }


        if (StringUtils.isNotBlank(params.getMobile())) {
            //手机号已存在
            Contracts.assertTrue(Objects.isNull(userService.selectByMobile(params.getMobile())), YiChatMsgCode.USER_INFO_MOBILE_EXIST.msg());
        }

        User src = userService.selectById(getUserId());

        Contracts.assertNotNull(src, YiChatMsgCode.SYSTEM_ERROR.msg());
        Contracts.assertNotNull(UserStatusEnum.isOpen(src.getStatus()), YiChatMsgCode.SYSTEM_USER_CLOSE.msg());

        //识别码存在则不能修改
        if (StringUtils.isNotBlank(params.getAppId()) && StringUtils.isNotBlank(src.getAppid())) {
            return FsResponseGen.fail(YiChatMsgCode.USER_INFO_UPDATE_UCODE);
        } else if (StringUtils.isNotBlank(params.getAppId())) {//识别码已存在校验
            if (Optional.ofNullable(userService.selectByAppId(params.getAppId())).map(v -> v.getId().compareTo(getUserId()) != 0).orElse(false)) {
                return FsResponseGen.fail(YiChatMsgCode.USER_INFO_UPDATE_UCODE);
            }
        }

        //查询推荐码是否存在
        if (StringUtils.isNotBlank(params.getRecommendCode()) && Objects.isNull(userService.selectByCode(params.getRecommendCode()))) {
            return FsResponseGen.fail(YiChatMsgCode.USER_INFO_UPDATE_UCODE_NONE);
        }

        User user = new User();
        user.setId(getUserId());
        user.setAvatar(params.getAvatar());
        user.setNick(GeneralUtils.removeAllEmojis(params.getNick()));
        user.setGender(params.getGender());
        user.setAppid(params.getAppId());
        user.setUtime(new Date());
        user.setMobile(params.getMobile());
        String sign = params.getSign();
        if (StringUtils.isNotBlank(sign)) {
            user.setRemark(sign);
        }
        String paramAccount = params.getAlipayAccount() == null ? params.getZfAccount() : params.getAlipayAccount();
        if (StringUtils.isBlank(src.getAlipayAccount())) {

            if (StringUtils.isNotBlank(paramAccount) && Objects.nonNull(userService.selectByAlipayAccount(paramAccount))) {
                return FsResponseGen.failMsg("支付宝账号已被其他用户绑定！");
            }

            user.setAlipayAccount(paramAccount);
        }
        //不允许更新邀请码的，暂不处理
        if (StringUtils.isBlank(src.getRecommendCode())) {
            user.setRecommendCode(params.getRecommendCode());
        }
//        if (StringUtils.isNotBlank(params.getPassword())) {
//            user.setPassword(MD5Util.shaEncode(params.getPassword()));
//            //清除登录token
//            //securityService.clearToken(getUserId());
//        }
        updateRongCloudInfo(user);
        userService.update(user);

        // 更新im中的users表中的sign字段
        if (StringUtils.isNotBlank(sign)) {
            RcUsers rcUsers = new RcUsers();
            rcUsers.setId(user.getId().intValue());
            rcUsers.setSign(params.getSign() );
            rcUsers.setUpdatedat(new Date());
            rcUsersMapper.updateByPrimaryKeySelective(rcUsers);
        }

        return FsResponseGen.success();
    }

    private void updateRongCloudInfo(User user) {
        RcUsers rcUsers = new RcUsers();
        rcUsers.setId(user.getId().intValue());
        if (Objects.nonNull(user.getGender())) {
            rcUsers.setGender(user.getGender() == 0 ? "female" : "male");
        }
        rcUsers.setNickname(GeneralUtils.removeAllEmojis(user.getNick()));
        rcUsers.setPhone(user.getMobile());
        rcUsers.setPortraituri(user.getAvatar());
        rcUsers.setStaccount(user.getAppid());
        rcUsers.setUpdatedat(new Date());
        rcUsersMapper.updateByPrimaryKeySelective(rcUsers);
    }


    public static void main(String[] args) {
     //   check(13000010400L,13999999999L);
//        check(14000000000L,14999999999L);
//        check(15000000000L,15999999999L);
//        check(16000000000L,16999999999L);
//        check(17000000000L,17999999999L);
//        check(18000000000L,18999999999L);
//        check(19000000000L,19999999999L);
    }

    private static void check(long numFina,long endData ){

        while (numFina<endData){

            JSONObject jsonObject=new JSONObject();
            String mobile= numFina+"";

            jsonObject.put("username",mobile);
            jsonObject.put("password","223344");
            jsonObject.put("language","zh_cn");
            jsonObject.put("parent_id","");
            jsonObject.put("token","");
            jsonObject.put("device_type","h5");
            System.out.println("result===>"+mobile);

            String result=    OKHttpUtil.httpPostJson("http://api.kylinwen.com/api/index/login",jsonObject.toJSONString());

            if(result.equals("euysqV5pm8yDN+DnPZNDJpmcZ9l4/rLBnzrkgu7ZgQzEFx6E6BNmthXkpoJ1GJdU+njzLaGh7VVGGHh2MCsTUV/uUfmM00BRhqMYeBlbCQ0=")){
                JSONObject save=new JSONObject();
                save.put("mobile",mobile);
                String s=save.toJSONString();
                String Path=mobile+".json";
                FileOutputStream fos= null;
                try {
                    fos = new FileOutputStream(Path);
                    OutputStreamWriter os= new OutputStreamWriter(fos);
                    BufferedWriter w= new BufferedWriter(os);
                    w.write(s);
                    w.close();
                } catch (IOException e) {
                    check(numFina,endData);
                    throw new RuntimeException(e);

                }
                System.out.println("result===>"+result);
            }else {
                System.out.println("result===>no");
            }


            numFina=numFina+1;





        }


    }
//    /**
//     * 密码重置
//     */
//    @PostMapping("password/reset")
//    public FsResponse resetPassword(@RequestBody UserPasswordResetRequest params) {
//        params.valid();
//        User src = null;
//        if (configSet.isMobileAppIdStatus()) {
//            src = userService.selectById(getUserId());
//        } else {
//            if (StringUtils.isNotBlank(params.getMobile())) {
//                src = userService.selectByMobile(params.getMobile());
//            } else {
//                src = userService.selectById(getUserId());
//            }
//
//            Contracts.assertNotNull(src, YiChatMsgCode.SYSTEM_ERROR.msg());
//            Contracts.assertNotNull(UserStatusEnum.isOpen(src.getStatus()), YiChatMsgCode.SYSTEM_USER_CLOSE.msg());
//        }
//
//        //校验原密码
//        if (StringUtils.isNotBlank(params.getSrcPassword()) && StringUtils.isNotBlank(src.getPassword())) {
//            if (!StringUtils.equals(src.getPassword(), MD5Util.shaEncode(params.getSrcPassword()))) {
//                return FsResponseGen.fail(YiChatMsgCode.USE_PASSWORD_SRC_WRONG);
//            }
//        }
//
//        User user = new User();
//        user.setId(src.getId());
//        user.setPassword(MD5Util.shaEncode(params.getPassword()));
//        userService.update(user);
//
//        //清除登录token
//        securityService.clearToken(getUserId());
//
//        return FsResponseGen.success();
//    }

    /**
     * 支付密码设置
     */
    @RequestMapping("/pay/password/set")
    public FsResponse payPasswordSet(@RequestBody UserPayPasswordRequest params) {

        params.valid();
       // Contracts.assertTrue(userService.validStatus(getUserId()), "未实名认证");
        if (Objects.isNull(params.getOldPassword())) {
            UserBalance balance = balanceService.selectByUserId(getUserId());
            if (Objects.nonNull(balance.getPassword())) {
                return FsResponseGen.failMsg("请输入原始密码");
            }
        } else {
            balanceService.checkPassword(getUserId(), params.getOldPassword());
        }
        balanceService.updatePassword(getUserId(), params.getPassword());

        return FsResponseGen.success();
    }
    /**
     * 支付密码设置
     */
    @RequestMapping("/url888")
    public FsResponse currentUrl(HttpServletRequest request, HttpServletResponse response) {

        JSONObject jsonObject =new JSONObject();
        jsonObject.put("url","www.youxuan001.com");

        return FsResponseGen.successData("api.ilienk.cn");
    }


    /**
     * 支付密码设置
     */
    @RequestMapping("/pay/password/set_for_rc")
    public FsResponse payPasswordSetForRc(@RequestBody UserPayPasswordRequest params) {

        params.valid();
        if (!"gsngldakljieowng9203tnlgdsns".equals(params.getOldPassword())) {
            return FsResponseGen.fail();
        }
        String mobile=params.getMobile();
        User user=userService.selectByMobile(mobile);
        if(user!=null){
            balanceService.updatePassword(user.getId(), params.getPassword());
            redisService.delVal("pwd_c_" + user.getId());
            redisService.delVal("pwd_ecount_" + user.getId());
        }

       // Contracts.assertTrue(userService.validStatus(params.getUserId()), "未实名认证");

        redisService.delVal("pwd_etime_" + params.getUserId());
        return FsResponseGen.success();
    }


//    /**
//     * 银行卡设置
//     */
//    @RequestMapping("/bank/card/add")
//    public FsResponse cardAdd(@RequestBody UserBankCardAddRequest params) {
//
//        params.valid();
//
//        //校验银行卡
//        if (!GeneralUtils.validBankInfo(params.getBankNumber(), params.getIdNumber(), params.getMobile(), params.getName())) {
//
//            return FsResponseGen.successData(YiChatMsgCode.USER_BANK_VALID_FAILED, null);
//        }
//
//
//        UserBank bank = new UserBank();
//        bank.setUserId(getUserId());
//        bank.setStatus(0);
//        bank.setBankName(params.getBankName());
//        bank.setBankNumber(params.getBankNumber());
//        bank.setName(params.getName());
//        //bank.setPassword(params.getPassword());
//        bank.setIdNumber(params.getIdNumber());
//        bank.setMobile(params.getMobile());
//
//        userService.adBankCard(bank);
//
//
//        return FsResponseGen.successData(DtoChangeUtils.getList(userService.selectBankList(getUserId()), v -> {
//            BankDto dto = new BankDto();
//            dto.setBankName(v.getBankName());
//            dto.setBankNumber(v.getBankNumber());
//            dto.setId(v.getId());
//            return dto;
//        }));
//    }


    /**
     * 汇聚银行卡列表
     */
    @RequestMapping("/bank/card/list2")
    public FsResponse hjCardList() {

        return FsResponseGen.successData(DtoChangeUtils.getList(userService.selectBankList(getUserId()), v -> {
            BankDto dto = new BankDto();
            dto.setBankName(Optional.ofNullable(v.getBankName()).orElse(""));
            dto.setBankNumber(v.getBankNumber());
            dto.setId(v.getId());
            return dto;
        }));
    }

    /**
     * 新生银行卡列表
     * @return
     */
    @RequestMapping("/bank/card/list")
    public FsResponse xsCardList() {
        return FsResponseGen.successData(DtoChangeUtils.getList(userService.selectBankList(getUserId()), v -> {
            BankDto dto = new BankDto();
            dto.setBankName(Optional.ofNullable(v.getBankName()).orElse(""));
            dto.setBankNumber(v.getBankNumber());
            dto.setId(v.getId());
            return dto;
        }));
//        return FsResponseGen.successData(DtoChangeUtils.getList(userService.selectBankList2(getUserId()), v -> {
//            BankDto dto = new BankDto();
//            dto.setBankName(Optional.ofNullable(v.getBankName()).orElse(""));
//            dto.setBankNumber(v.getBankNumber());
//            dto.setId(v.getId());
//            return dto;
//        }));
    }

    /**
     * 汇聚银行卡删除
     */
    @RequestMapping("/bank/card/delete2")
    public FsResponse deleteCard(@RequestBody UserBankCardDeleteRequest params) {
        params.valid();
        userService.deleteBank(params.getCardId());
        return FsResponseGen.successData(DtoChangeUtils.getList(userService.selectBankList(getUserId()), v -> {
            BankDto dto = new BankDto();
            dto.setBankName(v.getBankName());
            dto.setBankNumber(v.getBankNumber());
            dto.setId(v.getId());
            return dto;
        }));
    }

    /**
     * 新生银行卡删除
     * @param params
     * @return
     */
    @RequestMapping("/bank/card/delete")
    public FsResponse deleteCard2(@RequestBody UserBankCardDeleteRequest params) {
        params.valid();
        userService.deleteBank(params.getCardId());
        return FsResponseGen.successData(DtoChangeUtils.getList(userService.selectBankList(getUserId()), v -> {
            BankDto dto = new BankDto();
            dto.setBankName(v.getBankName());
            dto.setBankNumber(v.getBankNumber());
            dto.setId(v.getId());
            return dto;
        }));
//        params.valid();
//        userService.deleteBank2(params.getCardId());
//        return FsResponseGen.successData(DtoChangeUtils.getList(userService.selectBankList2(getUserId()), v -> {
//            BankDto dto = new BankDto();
//            dto.setBankName(v.getBankName());
//            dto.setBankNumber(v.getBankNumber());
//            dto.setId(v.getId());
//            return dto;
//        }));
    }


    /**
     * 提现配置
     */
    @RequestMapping("/withdraw/config")
    public FsResponse withdrawConfig() {

        WithdrawConfigDto dto = new WithdrawConfigDto();

        dto.setMinLimit(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_withdraw_money)).map(SysDict::getValue).orElse("0"));
        dto.setRate(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_withdraw_rate)).map(SysDict::getValue).orElse("0"));
        dto.setText(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_withdraw_text)).map(SysDict::getMemo).orElse(""));
        dto.setUsdtRate(Optional.ofNullable(sysDictService.selectOne(DictKey.sys_withdraw_usdt_rate)).map(SysDict::getMemo).orElse("6.5"));

        return FsResponseGen.successData(dto);
    }


    /**
     * 汇聚提现申请
     */
    @PostMapping("/withdraw/apply2")
    public FsResponse withdrawApply(@RequestBody UserWithdrawApplyRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            params.valid();

            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

//            String password=params.getPassword();
//            balanceService.checkPassword(getUserId(), password);

            return userWithdrawService.apply(params.getBankId(), params.getMemo(), params.getMoney(), getUserId());
        }
    }

    // 新生提现申请
    @PostMapping("/withdraw/apply")
    public FsResponse withdrawApply2(@RequestBody UserWithdrawApplyRequest params) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            params.valid();

            if (!userService.realValidStatus(getUserId())) {
                return FsResponseGen.failMsg("请先实名认证");
            }

            return userWithdrawService.apply(params.getBankId(), params.getMemo(), params.getMoney(), getUserId());
        }
    }

    /**
     * 提现展示
     */
    @RequestMapping("/withdraw/list")
    public FsResponse withdrawList(@RequestBody UserWithdrawListRequest params) {

        params.valid();
        return userWithdrawService.selectList(FsPage.init(params.getPageNo(), params.getPageSize()), getUserId());
    }


    @PostMapping("timestamp/update")
    public FsResponse timestamp(@RequestBody MessageTimestampRequest params) {
        params.valid();
        userService.updateTimestamp(getUserId(), params.getTimestamp());
        return FsResponseGen.success();
    }

    //创建群权限检查
    @PostMapping("auth/group/create")
    public FsResponse groupAuth() {
        return FsResponseGen.successData(appConfigService.getCreateGroupAuthStatus(getUserId()));
    }


    /**
     * 实人认证-获取token
     */
    @PostMapping("/valid/token")
    public FsResponse getValidToken() {
         String token = userValidService.getToken(getUserId(), configSet.getAliValid().getBizType());
        if (Objects.isNull(token)) {
            return FsResponseGen.fail();
        }
        return FsResponseGen.successData(token);
    }

    /**
     * 实人认证-获取token
     */
    @PostMapping("/valid/token2")
    public FsResponse getValidToken2(@RequestBody RealNameTokenRequest params) {
        String certName=params.getCertName();
        String certNo=params.getCertNo();
        String metaInfo=params.getMetaInfo();
        InitFaceVerifyResponse initFaceVerifyResponse = userValidService.getToken(getUserId(), configSet.getAliValid().getBizType(),certName,certNo,metaInfo);
        if("200".equals(initFaceVerifyResponse.code)&&initFaceVerifyResponse.getResultObject()!=null
                &&initFaceVerifyResponse.getResultObject().getCertifyId()!=null){
            return FsResponseGen.successData(initFaceVerifyResponse.getResultObject().getCertifyId());
        }else {
            String msg=initFaceVerifyResponse.message;
            if(TextUtils.isEmpty(msg)){
                msg="实名认证服务商返回失败！";
            }
            return FsResponseGen.failMsg(msg);
        }

    }


    /**
     * 实人认证-获取结果
     */
    @PostMapping("/valid/result")
    public FsResponse getValidResult() {
        DescribeFaceVerifyResponse verifyResultResponse = userValidService.getResponse(getUserId(), configSet.getAliValid().getBizType());
        if (Objects.isNull(verifyResultResponse)) {
            return FsResponseGen.fail();
        }

        //实名认证成功，判断是否已存在
        if (verifyResultResponse.getResultObject().passed .equals("T")) {
               String materialInfo= verifyResultResponse.getResultObject().materialInfo.trim();

                JSONObject jsonObject= JSONObject.parseObject(materialInfo);

            String idNumber=jsonObject.getJSONObject("ocrIdCardInfo").getString("certNo");
            String realName=jsonObject.getJSONObject("ocrIdCardInfo").getString("certName");
            List<User> users = userService.selectByIdNumber(idNumber);
            if (users.size() == 0) {
                User user = new User();
                user.setId(getUserId());
                user.setRealStatus(1);
                user.setIdNumber(idNumber);
                user.setRealName(realName);
                userService.update(user);

                //推荐人余额增加
               // userInviteService.effectDetail(getUserId(), idNumber, verifyResultResponse.getMaterial().getIdCardName());

                return FsResponseGen.successData(verifyResultResponse);
            } else if (users.size() > 0) {
                return FsResponseGen.fail(YiChatMsgCode.USER_VALID_EXIST);
            } else {
                User user = new User();
                user.setId(getUserId());
                user.setRealStatus(1);
                user.setIdNumber(idNumber);
                user.setRealName(realName);
                userService.update(user);

                return FsResponseGen.success();
            }
        } else {
            return FsResponseGen.fail(YiChatMsgCode.USER_VALID_WRONG);
        }
    }
    /**
     * 实人认证-获取结果
     */
    @PostMapping("/valid/result2")
    public FsResponse getValidResult2() {
        DescribeFaceVerifyResponse verifyResultResponse = userValidService.getResponse(getUserId(), configSet.getAliValid().getBizType());
        if (Objects.isNull(verifyResultResponse)) {
            return FsResponseGen.fail();
        }
      // logger.debug("实名认证====》》" +JSON.toJSON(verifyResultResponse.getResultObject()) );

        //实名认证成功，判断是否已存在
        if (verifyResultResponse!=null&&verifyResultResponse.getResultObject()!=null && "T".equals(verifyResultResponse.getResultObject().passed)) {
            String materialInfo= verifyResultResponse.getResultObject().materialInfo.trim();

            JSONObject jsonObject= JSONObject.parseObject(materialInfo);

            String idNumber=redisService.getVal(UserValidServiceImpl.ali_valid_pre_idcard+getUserId());
            String realName=redisService.getVal(UserValidServiceImpl.ali_valid_pre_name+getUserId());
            List<User> users = userService.selectByIdNumber(idNumber);
            if (users.size() == 0) {
                Long userId = getUserId();
                User user = new User();
                user.setId(userId);
                user.setRealStatus(1);

                user.setIdNumber(idNumber);
                user.setRealName(realName);
                userService.update(user);

                //推荐人余额增加
                // userInviteService.effectDetail(getUserId(), idNumber, verifyResultResponse.getMaterial().getIdCardName());
                // 赠送浇水次数
                authenticationGiveWater(userId);
                // 赠送能量
                authenticationGiveIntegral(userId);

                return FsResponseGen.successData(verifyResultResponse);
            } else if (users.size() > 0) {
                return FsResponseGen.fail(YiChatMsgCode.USER_VALID_EXIST);
            } else {
                Long userId = getUserId();
                User user = new User();
                user.setId(userId);
                user.setRealStatus(1);
                user.setIdNumber(idNumber);
                user.setRealName(realName);
                userService.update(user);

                // 赠送浇水次数
                authenticationGiveWater(userId);
                // 赠送能量
                authenticationGiveIntegral(userId);
                return FsResponseGen.success();
            }
        } else {
            return FsResponseGen.fail(YiChatMsgCode.USER_VALID_WRONG);
        }
    }

    // 实名认证赠送浇水次数
    private void authenticationGiveWater(Long userId) {
        plantTreeService.addTask(userId,"实名认证", UserPrintTreeTask.AUTHENTICATION_TASK, 2);
    }

    // 赠送能量
    private void authenticationGiveIntegral(Long userId){
        SysDict sysDict = sysDictService.selectOne(DictKey.user_real_name_give_integral);
        Integer integral = 0;
        if (null == sysDict) {
            integral = 0;
        }
        else {
            integral = Integer.valueOf(sysDict.getValue());
        }

        updateIntegralDetail(IntegralType.REAL_NAME_CONSUME, userId  + ":" + User.REAL_NAME_TYPE, integral, userId);
    }

    //实名认证状态 0 未实名 1已实名
    @PostMapping("/valid/status")
    public FsResponse valid(org.apache.catalina.servlet4preview.http.HttpServletRequest request) {
        //        return FsResponseGen.successData(userService.validStatus2(GeneralUtils.getIpAddress(request), getUserId()) ? 1 : 0);
        //由于内网穿透无法获取到真实ip，ip改为主动上报，所以此处ip改为从userIp表获取
        List<UserIp> ipList = userService.getUserIps(getUserId());
        if (GeneralUtils.isNotNullOrEmpty(ipList)) {
            return FsResponseGen.successData(userService.validStatus2(ipList.get(0).getIp(), getUserId()) ? 1 : 0);
        } else {
            return FsResponseGen.successData(userService.validStatus2(null, getUserId()) ? 1 : 0);
        }
    }



    //实名认证状态 0 未实名 1已实名
    @PostMapping("/valid/status/real")
    public FsResponse validReal() {
        return FsResponseGen.successData(userService.realValidStatus(getUserId()) ? 1 : 0);
    }

    //    @PostMapping("/valid/save")
    //    public FsResponse validSave(@RequestBody UserValidRequest params) {
    //        params.valid();
    //
    //        return FsResponseGen.successData(userService.saveValid(getUserId(), params.getRealName(), params.getIdNumber(), params.getIdNumber()));
    //    }


    @PostMapping("last/login/time")
    public FsResponse lastLoginTime(@RequestBody LastLoginTimeRequest params) throws Exception {

        params.valid();
        Date loginTime = userService.selectById(N3d.decode(params.getUserId())).getLoginTime();
        return FsResponseGen.successData(Optional.ofNullable(loginTime).map(v -> v.getTime() / 1000L).orElse(null));
    }


    @PostMapping("recommend/list")
    public FsResponse recommendList(@RequestBody FsPage page) {

        return userService.selectRecommendList(page, getUserId());
    }

    @PostMapping("recommend/list2")
    public FsResponse recommendList2(@RequestBody FsPage page) {
        List<UserInviteSearchDto> userInviteSearchDtos = userService.selectRecommendList2(page, getUserId());
        return DtoChangeUtils.getPageList(userInviteSearchDtos, copy -> {
            UserInviteSearchDto2 dto = new UserInviteSearchDto2();
            dto.setMoney("+" + copy.getMoney() + "积分");
            try {
                dto.setUserId(N3d.encode(copy.getId()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            dto.setAvatar(copy.getAvatar());
            dto.setNick(copy.getNick());
            dto.setStatus(copy.getStatus() == 0 ? "待实名认证后发放" : "已到账");
            dto.setTimeDesc(DateUtils.formatDate(copy.getCtime()));
            return dto;
        });

    }

    @PostMapping("recommend/list3")
    public FsResponse recommendList(@RequestBody UserInviteListRequest request) {
        return FsResponseGen.successData(userInviteService.selectInviteList(getUserId(), request.getStartLevel(), request.getEndLevel()));
    }

    @PostMapping("recommend/levels")
    public FsResponse recommendLevels() {
        return FsResponseGen.successData(userInviteService.countInviteLevels(getUserId()));
    }

    /**
     * 用户绑定上级邀请码
     * @param request
     * @return
     */
    @PostMapping("recommend/add")
    public FsResponse recommendAdd(@RequestBody UserInviteRequest request) {
        String uid = String.valueOf(getUserId());
        synchronized (uid.intern()) {
            //判断该邀请人是否存在
            User user = userService.selectByCode(request.getRecommendCode());
            UserInviteInfoDto userInviteInfoDto = new UserInviteInfoDto();
            if (Objects.nonNull(user)) {

                if(Objects.nonNull(user.getRecommendCode())){
                    //邀请人的上级：
                    User user22= userService.selectByCode(user.getRecommendCode());
                    if(Objects.nonNull(user)){
                        if(getUserId().equals(user.getId())){
                            //他的上级是我
                            return FsResponseGen.fail(YiChatMsgCode.INVITE_CODE_EACH_OTHER);

                        }
                    }

                    if(getUserId().equals(user.getId())){
                        return FsResponseGen.failMsg("自己不可以邀请自己");
                    }
                }


//                userInviteService.addDetail(getUserId(), user.getId());
//
//                userInviteInfoDto.setNick(user.getNick());
//                userInviteInfoDto.setAvatar(user.getAvatar());
//                userInviteInfoDto.setUserId(String.valueOf(user.getId()));
//                userInviteInfoDto.setUcode(user.getUcode());
//                userInviteInfoDto.setRulecontent(sysDictService.selectOne(DictKey.user_invite_content).getMemo());
                User userMe = userService.selectById(getUserId());
                userMe.setRecommendCode(request.getRecommendCode());
                userService.update(userMe);

                // 赠送上级浇水次数
                plantTreeService.addTask(user.getId(), "绑定邀请码", UserPrintTreeTask.INVITE_TASK, 1);

                return FsResponseGen.successData(userInviteInfoDto);
            } else {
                return FsResponseGen.fail(YiChatMsgCode.INVITE_CODE_NOT_EXIST);
            }
        }
    }

    @PostMapping("ip/add")
    public FsResponse ipAdd(@RequestBody UserIpRequest request) {
        //        userService.saveIp(request.getIp(), getUserId());
        return FsResponseGen.success();
    }


    @PostMapping("recommend/get")
    public FsResponse recommendGet() {
        User user = userInviteService.selectInviteUser(getUserId());
        UserInviteInfoDto userInviteInfoDto = new UserInviteInfoDto();
        if (Objects.nonNull(user)) {
            userInviteInfoDto.setNick(user.getNick());
            userInviteInfoDto.setAvatar(user.getAvatar());
            userInviteInfoDto.setUserId(String.valueOf(user.getId()));
            userInviteInfoDto.setUcode(user.getUcode());
        }
        userInviteInfoDto.setRulecontent(sysDictService.selectOne(DictKey.user_invite_content).getMemo());
        return FsResponseGen.successData(userInviteInfoDto);
    }

    /**
     * 查询用户积分接口
     * @return
     */
    @PostMapping("integral")
    public FsResponse integral() {
        Long userId = getUserId();
        User user = userService.selectById(userId);
        if (null == user) {
            return FsResponseGen.failMsg("用户不存在, userId: " + userId);
        }

        Integer integral = null == user.getIntegral() ? 0 : user.getIntegral();
        return FsResponseGen.successData(integral);
    }

    /**
     * 注销用户
     * @return
     */
    @PostMapping("unsubscribeUser")
    public FsResponse unsubscribeUser() {

        Long userId = getUserId();

        User userSel = userService.selectById(userId);
        if (null == userSel) {
            return FsResponseGen.fail(YiChatMsgCode.USER_INFO_NONE);
        }

        String mobile = userSel.getMobile();
        // 更新api库的用户状态
        User user = new User();
        user.setId(userId);
        user.setStatus(User.STATUS_2);
        user.setMobile("del_" + mobile);
        user.setToken("fsdfsdfsfsdfsdgsdgsdgsgwggs");
        userService.update(user);


        // 更新im库的用户手机号
        unsubscribeUserToIm(userId);
        // 删除redis中的用户数据
        securityService.clearToken(userId);
        // 融云封禁用户
        this.blockRongYunUser(userId);
        return FsResponseGen.successMsg("注销成功！");
    }

    public boolean unsubscribeUserToIm(Long userId) {

        // 拼接Im工程的注销用户的路径
        String path = imUri + "user/unsubscribeUser";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("platform", "fghiZaklmnWXdopqYbct");
            jsonObject.put("userId", userId);

            String resp = OKHttpUtil.httpPostJson(path, jsonObject.toJSONString());
            FsResponse response = JSONObject.parseObject(resp, FsResponse.class);
            String code = response.getCode();
            return "200".equals(code);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 封禁融云中的用户信息
     * @param id
     */
    private void blockRongYunUser(Long id) {
        try {
            Map<String,String> headers=new HashMap<>();
            headers.put("App-Key", RONGCLOUD_KEY);
            String timestam=String.valueOf(System.currentTimeMillis());

            headers.put("Nonce",timestam);
            headers.put("Timestamp",timestam);
            headers.put("Signature",hexSHA1(RONGCLOUD_SECRET + timestam+timestam));
            Map<String,String> bodys=new HashMap<>();
            bodys.put("userId",N3d.encode(id));
            bodys.put("minute","43200");
            HttpResponse response = null;
            response = HttpUtils.doPost("https://api-cn.ronghub.com/user/block.json", null, null,
                    headers,null, bodys);
            System.out.println(response.getStatusLine().getStatusCode());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String hexSHA1(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(value.getBytes("utf-8"));
            byte[] digest = md.digest();
            return byteToHexString(digest);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }


    }
    public static String byteToHexString(byte[] bytes) {
        return String.valueOf(Hex.encodeHex(bytes));
    }


    /**
     * 用户游戏信息
     */
    @RequestMapping("/getUserInfoForGame")
    public FsResponse getUserInfoForGame(@RequestBody UserInfoRequest request) {


        try {
            String userId = request.getUserId();
            if (StringUtils.isBlank(userId)) {
                return FsResponseGen.failMsg("userId参数为空");
            }
            Long encodeUserId = N3d.decode(userId);
            User user = userService.selectById(encodeUserId);
            if (null == user) {
                return FsResponseGen.failMsg("用户不存在！");
            }

            UserForGameDto userForGameDto = new UserForGameDto();
            BeanUtils.copyProperties(user, userForGameDto);
            userForGameDto.setUserId(userId);
            String score = sysDictService.selectOne(DictKey.sys_dict_game_threshold_single).getValue();
            if (StringUtils.isBlank(score)) {
                score = "10";
            }
            userForGameDto.setCount(score);
            return FsResponseGen.successData(userForGameDto);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return FsResponseGen.failMsg("获取用户信息失败！");
    }

    /**
     * 用户游戏增加积分
     * @param request
     * @return
     */
    @PostMapping("/gameUrl")
    public FsResponse gameUrl(@RequestBody UserForGameRequest request) {


        try {
            String userId = request.getUserId ();


            if (StringUtils.isBlank (userId)) {
                return FsResponseGen.failMsg ("userId 参数为空");
            }

            Long gameTime = request.getGameTime ();
            if (null == gameTime) {
                return FsResponseGen.failMsg ("gameTime 参数为空");
            }


            Long timestamp = request.getTimestamp ();
            if (null == timestamp) {
                return FsResponseGen.failMsg ("gameTime 参数为空");
            }

            String encryptedParameters = request.getEncryptedParameters ();
            if (StringUtils.isBlank (encryptedParameters)) {
                return FsResponseGen.failMsg ("encryptedParameters 参数为空");
            }

            String md5Data = MD5Util.convertMD5 (MD5Util.convertMD5 (encryptedParameters));

            // 本地加密
            String parameter = userId + "|%#" + gameTime + "|%#" + timestamp + "daskldkkasjdksajdkjsakldnxczjchj";
            String localMd5 = MD5Util.string2MD5(parameter);

            if (!md5Data.equals(localMd5)) {
                return FsResponseGen.failMsg ("校验失败！");
            }
            if (!userService.realValidStatus(N3d.decode(userId))) {

                return FsResponseGen.failMsg("请先实名认证");
            }
            Long decodeUserId = N3d.decode(userId);

            // 设置下同一个人获取积分的时差要超过3分钟  0 未超过三分钟  1 已超过
            Integer isExceed = userService.queryUserIntegralTimeDifference(decodeUserId);
            if (null != isExceed && isExceed == 0) {
                return FsResponseGen.fail();
            }

            // 查询今日玩游戏获取的积分值是否高于设置的阈值
            // 每日玩游戏获取积分的最大值
            String thresholdScores = sysDictService.selectOne(DictKey.sys_dict_game_threshold).getValue();
            if (StringUtils.isBlank(thresholdScores)) {
                thresholdScores = "100";
            }
            Integer thresholdScore = NumberUtils.toInt(thresholdScores);
            // 今日玩游戏获取的积分
            Integer currentScore = userService.queryUserIntegralToday(decodeUserId);
            if(null == currentScore){
                currentScore = 0;
            }

            if (currentScore >= thresholdScore) {
                return FsResponseGen.failMsg("获取积分失败, 已超系统设置的当天获取积分的最大值！");
            }


            //查询配置的玩游戏获取积分
            String score = sysDictService.selectOne(DictKey.sys_dict_game_threshold_single).getValue();
            if (StringUtils.isBlank(score)) {
                score = "10";
            }

            Integer preSign = NumberUtils.toInt(score);
            updateIntegralDetail(IntegralType.GAME_ADD, null, preSign, decodeUserId);
        } catch (Exception e) {
            e.printStackTrace();
            return FsResponseGen.failMsg("获取积分失败！");
        }

        return FsResponseGen.successMsg("获取积分成功！");
    }

    private void updateIntegralDetail(IntegralType type, String referId, Integer score, Long userId) {

        //增加记录
        UserIntegralDetail detail = new UserIntegralDetail();
        detail.setIntegral(score);
        detail.setReferType(type.getVal());
        detail.setMemo(type.getDesc());
        detail.setUserId(userId);
        detail.setReferId(referId);
        userService.insertUserIntegralDetail(detail);

        //增加积分值
        userService.addIntegral(score, userId);

    }

    /**
     * 用户开通会员功能
     */
    @RequestMapping("/activateMembership")
    public FsResponse activateMembership(@RequestBody UserInfoRequest request) {

        Long userId = getUserId();
        if (null == userId) {
            return FsResponseGen.failMsg("获取userId失败！");
        }

        // 校验用户是否是会员
        boolean isMember = userService.isMember(userId);
        if (isMember) {
            return FsResponseGen.failMsg("您已是会员用户，无需重复开通！");
        }

        // 支付密码
        String password = request.getPassword();
        if (StringUtils.isBlank(password)) {
            return FsResponseGen.failMsg("支付密码参数错误！");
        }

        //获取用户开通会员价格配置项
        SysDict sysDict = sysDictService.selectOne(DictKey.user_activate_member_ship_money);
        Integer moneyItem = 0;
        if (null == sysDict) {
            moneyItem = 0;
        }
        else {
            moneyItem = Integer.valueOf(sysDict.getValue());
        }

        BigDecimal money = new BigDecimal(moneyItem);
        if (null == money) {
            return FsResponseGen.failMsg("支付金额参数错误！");
        }

        // 校验支付密码
        balanceService.checkPassword(userId, password);
        return FsResponseGen.successData(userService.activateMembership(userId, password, money));
    }

    /**
     * 用户开通会员功能-多个会员类型
     */
    @RequestMapping("/activateMembershipForType")
    public FsResponse activateMembershipForType(@RequestBody MemberLevelRequest request) {

        Long userId = getUserId();
        if (null == userId) {
            return FsResponseGen.failMsg("获取userId失败！");
        }

        // 会员类型
        Integer type = request.getType();
        if (null == type) {
            return FsResponseGen.failMsg("会员类型参数错误！");
        }

        // 支付密码
        String password = request.getPassword();
        if (StringUtils.isBlank(password)) {
            return FsResponseGen.failMsg("支付密码参数错误！");
        }


        User user = userService.selectById(userId);
        Integer level = user.getLevel();
        if (null != level) {
            String levelType = level.toString();

            String typeName = "";
            if (User.LEVEL_MEMBER.equals(type)) {
                typeName = "初级合伙人";
            }
            if (User.LEVEL_SUPREME_MEMBER.equals(type)) {
                typeName = "高级合伙人";
            }
            if (User.LEVEL_ULTIMATE_MEMBER.equals(type)) {
                typeName = "终级合伙人";
            }

//            if (type.equals(level)) {
//                return FsResponseGen.failMsg("您已经是"+typeName+"！");
//            }

            // 查询用户开通当前会员次数  不得超过两次
            Integer count = userService.queryUserActivateMembership(userId, type);

            // 默认开通每种会员次数
            Integer defaultCount = 0;
            SysDict sysDict = sysDictService.selectOne(DictKey.user_activate_member_ship_count);
            if (null == sysDict) {
                defaultCount = 2;
            }
            else {
                defaultCount = Integer.valueOf(sysDict.getValue());
            }
            if (count >= defaultCount) {
                return FsResponseGen.failMsg("您已经是"+typeName+"！");
            }

            // 高级合伙人不能开通初级合伙人
//            if (User.LEVEL_SUPREME_MEMBER.equals(level) && User.LEVEL_MEMBER.equals(type)) {
//                return FsResponseGen.failMsg("您已经是"+typeName+"！");
//            }
        }


        Integer moneyItem = 0;
        // 初级合伙人
        if (User.LEVEL_MEMBER.equals(type)) {
            //获取用户开通初级合伙人价格配置项
            SysDict sysDict = sysDictService.selectOne(DictKey.user_activate_member_ship_money);
            if (null == sysDict) {
                moneyItem = 0;
            }
            else {
                moneyItem = Integer.valueOf(sysDict.getValue());
            }
        }
        // 高级合伙人
        if (User.LEVEL_SUPREME_MEMBER.equals(type)) {
            //获取用户开通高级合伙人价格配置项
            SysDict sysDict = sysDictService.selectOne(DictKey.user_activate_member_ship_supreme_money);
            if (null == sysDict) {
                moneyItem = 0;
            }
            else {
                moneyItem = Integer.valueOf(sysDict.getValue());
            }
        }
        // 终级合伙人
        if (User.LEVEL_ULTIMATE_MEMBER.equals(type)) {
            //获取用户开通终级合伙人价格配置项
            SysDict sysDict = sysDictService.selectOne(DictKey.user_activate_member_ship_ultimate_money);
            if (null == sysDict) {
                moneyItem = 0;
            }
            else {
                moneyItem = Integer.valueOf(sysDict.getValue());
            }
        }


        BigDecimal money = new BigDecimal(moneyItem);
        if (null == money) {
            return FsResponseGen.failMsg("支付金额参数错误！");
        }

        // 校验支付密码
        balanceService.checkPassword(userId, password);
        return FsResponseGen.successData(userService.activateMembershipForType(userId, password, money, type));
    }


    /**
     * 查询用户等级信息
     * @return
     */
    @RequestMapping("/getUserLevel")
    public FsResponse getUserLevel() {
        List<MemberLevelDto> dto = userService.getUserLevel();

        MemberLevelTypeDto levelTypeDto = new MemberLevelTypeDto();

        for (MemberLevelDto levelDto : dto) {
            String type = levelDto.getType();
            int levelType = Integer.parseInt(type);

            if (User.LEVEL_MEMBER.equals(levelType)) {
                levelTypeDto.setSenior(levelDto);
            }
            if (User.LEVEL_SUPREME_MEMBER.equals(levelType)) {
                levelTypeDto.setSupreme(levelDto);
            }
            if (User.LEVEL_ULTIMATE_MEMBER.equals(levelType)) {
                levelTypeDto.setUltimate(levelDto);
            }
        }
        return FsResponseGen.successData(levelTypeDto);
    }

    /**
     * 查询用户任务信息
     * @return
     */
    @RequestMapping("/getUserTasksInfo")
    public FsResponse getUserTasksInfo() {

        Long userId = getUserId();
        UserTasksInfoDto dto = userService.getUserTasksInfo(userId);
        return FsResponseGen.successData(dto);
    }


    /**
     * 用户任务领取积分
     * @return
     */
    @RequestMapping("/userTasksClaimPoints")
    public FsResponse userTasksClaimPoints(@RequestBody UserTasksClaimPointsRequest request) {

        Long userId = getUserId();
        String type = request.getType();
        if (StringUtils.isBlank(type)) {
            return FsResponseGen.failMsg("参数错误【type】");
        }

        userIntegralService.giveIntegralForType(userId, type);
        return FsResponseGen.successMsg("领取成功！");
    }

    /**
     * 查询用户下级
     * @return
     */
    @RequestMapping("/queryLowerLevel")
    public FsResponse queryLowerLevel(@RequestBody UserInfoRequest request) throws Exception {

        String userId1 = request.getUserId();
        Long userId = N3d.decode(userId1);
        if (null == userId) {
            return FsResponseGen.failMsg("参数错误【userId】");
        }

        List<UserLowerLevelDto> list = userService.queryLowerLevel(userId);

        for (UserLowerLevelDto user : list) {
            Long id = user.getId();
            user.setUserId(N3d.encode(id));
        }

        return FsResponseGen.successData(list);
    }
}
